package com.example.springboottestgit.config;


import com.example.springboottestgit.bean.BusinessException;
import com.example.springboottestgit.bean.CommonException;
import com.example.springboottestgit.bean.ResultMsg;
import com.example.springboottestgit.enums.ExceptionCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;
import java.util.Locale;

@RestControllerAdvice
public class GlobalHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalHandler.class);
    @Resource
    private MessageSource messageSource;

    @ExceptionHandler(Throwable.class)
    @ResponseBody //表示拦截json
    public ResultMsg<String> exceptionHandler(Exception e) {
        String logMsg = "";
        ResultMsg<String> ret = null;
        if (e instanceof CommonException) {
            CommonException commonException = (CommonException) e;
            return ResultMsg.fail(commonException.getCode(), commonException.getDesc());
        } else if (e instanceof BusinessException) {
            BusinessException bizException = (BusinessException) e;
            String code = bizException.getCode();
            if(code.charAt(3)=='1'){
                return ResultMsg.fail(code, bizException.getDesc());
            }
            ret = ResultMsg.fail(ExceptionCodeEnum.BUSINESS_ERROR.getCode(), ExceptionCodeEnum.BUSINESS_ERROR.getMessage());
        } else {
            log.error(e.getMessage());
            ret = ResultMsg.fail("系统异常");
        }
        return ret;
    }

    public String getMessage(String key, String... args) {
        try {
            System.out.println("LocaleContextHolder.getLocale() = " + LocaleContextHolder.getLocale());
            return messageSource.getMessage(key, args, LocaleContextHolder.getLocale());
        } catch (Exception ex) {
            System.out.println("Locale.getDefault() = " + Locale.getDefault());
            return messageSource.getMessage(key, args, Locale.getDefault());
        }
    }
}
